import 'package:jyofservice/bean/xiafa_person_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/generated/json/base/json_convert_content.dart';
import 'package:jyofservice/util/ShowQRCode.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/gongdandiaodu/DealDiaoDu.dart';
import 'package:jyofservice/bean/charge_data_entity.dart';
import 'package:jyofservice/bean/show_file_list_entity.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:jyofservice/bean/diaodu_detail_entity.dart';
import 'package:jyofservice/sql/DatabaseHelper.dart';
import 'package:jyofservice/util/PhotoGalleryPage.dart';
import 'package:jyofservice/util/SlideRoute.dart';
import 'package:jyofservice/gongdandiaodu/HistroyMenu.dart';
import 'package:jyofservice/gongdandiaodu/CommonUnit.dart';
import 'package:jyofservice/gongdandiaodu/WorkRecord.dart';
import 'package:url_launcher/url_launcher.dart';

class DiaoDuDetail extends StatefulWidget {
  String? LSH;
  bool? is0ffstage;
  String? view;
  bool? isDeliver;
  //是否接单超时 是和否
  String? isjdyq;
  //接单时限
  String? jdsxTime;
  DiaoDuDetail({this.LSH, this.is0ffstage, this.view,this.isDeliver,this.isjdyq,this.jdsxTime});

  @override
  _DiaoDuDetailState createState() => _DiaoDuDetailState();
}

class _DiaoDuDetailState extends State<DiaoDuDetail> {
  DiaoduDetailDataData? detailEntity = new DiaoduDetailDataData();
  late SharedPreferences sharedPreferences;
  TextEditingController ideaController = TextEditingController();
  TextEditingController deliverController = TextEditingController();
  ChargeDataDataData? sfInfoEntity;
  String? detailStr;
  String? key;
  //工单处理附件
  List<ShowFileListData> fileList = [];
  List showPhotoList = [];
  //接单附件
  List<ShowFileListData> fileJdList = [];
  List showPhotoJdList = [];

  bool isloading = false;
  bool? _isShow = true;
  bool isDelay = true;
  //工单退回备注
  final _bzTextEditingController = TextEditingController();
  List<XiafaPersonData> personLists = [];
  late XiafaPersonEntity personEntity;
  String ss ='';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //标记已读 2021-07-14修改 原因:部分已处理完成工单状态还显示未读
    if (widget.view == "GetMySelfWaitDoWorkConfirm" && detailEntity!.isRead != 1) {
      remarkIsRead().then((value) {
        //设置已读成功后 请求详情数据
        if(value["Code"] == "200") {

          getDetailData().then((value) {
            getFeeState();
            getSFData();
          });

          getFujianInfo();
          getJieDanFujianInfo();

        }
      });
    } else {

      getDetailData().then((value) {
        getFeeState();
        getSFData();
      });

      getFujianInfo();
      getJieDanFujianInfo();

    }

    _isShow = widget.is0ffstage;
  }

  Future remarkIsRead() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());
    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/markworkformisread",
        data: data);
    print(response.data.toString());
    if (response.data["Code"] != "200") {
      Fluttertoast.showToast(msg: response.data["Msg"]);
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
    } else {
      detailEntity!.isRead = 1;
      if (mounted) {
        setState(() {});
      }
    }
    return response.data;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('工单详情',
            style: TextStyle(
                color: Colors.white, fontSize: ScreenUtil().setSp(45))),
        actions: <Widget>[
          Offstage(
            offstage:
                widget.view == "GetMyAllFinishWork" && detailEntity!.ifhf == 2
                    ? true
                    : true, //只有青铜峡项目有评价功能, 2021-10-06修改
            child: TextButton(
              onPressed: () {
                showQr(context);
              },
              child: Text(
                '评价',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
          PopupMenuButton<String>(
            icon: Icon(Icons.more_horiz),
            offset: Offset(0, 20),
            itemBuilder: (BuildContext context){
              return widget.view=="GetMyAndChildrenWorkForm"|| widget.view=="GetMySelfWaitDoWorkConfirm"?<PopupMenuItem<String>>[
              this.SelectView('历史工单', 'B'),
              this.SelectView('同单元工单', 'C'),
              this.SelectView('工单日志', 'D'),
                //只有青铜峡项目有退回功能, 2021-10-06修改
              // this.SelectView('退回工单', 'E'),
            ]:<PopupMenuItem<String>>[
                this.SelectView('历史工单', 'B'),
                this.SelectView('同单元工单', 'C'),
                this.SelectView('工单日志', 'D'),
              ];
              },
            onSelected: (String action) {
              // 点击选项的时候
              switch (action) {
                case 'E':
                  showAlertReset();
                  break;
                case 'B':
                  Navigator.of(context).push(SlideRoute().createRoute(
                      HistroyPage(
                          sfbm: detailEntity!.sfbm, xqid: detailEntity!.allName)));
//                  NavigatorUtil.goHistoryMenu(
//                      context, detailEntity.sfbm, detailEntity.xqId);
                  break;
                case 'C':
                  Navigator.of(context).push(SlideRoute().createRoute(
                      CommonUnitPage(
                          sfbm: detailEntity!.sfbm, xqid: detailEntity!.xqId)));
//                  NavigatorUtil.goCommonUnit(
//                      context, detailEntity.sfbm, detailEntity.xqId);
                  break;
                case 'D':
                  Navigator.of(context).push(
                      SlideRoute().createRoute(WorkRecord(LSH: widget.LSH)));
//                  NavigatorUtil.goWorkRecord(context, widget.LSH);
                  break;
              }
            },
          ),
        ],
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Stack(
              alignment: Alignment(0.5, 0.5),
              children: <Widget>[
                SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Container(
                        color: Colors.blue,
                        width: ScreenUtil().screenWidth,
                        height: ScreenUtil().setHeight(100),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            SizedBox(
                              width: ScreenUtil().setWidth(30),
                            ),
                            Expanded(
                                child: Container(
                              child: Text(
                                detailEntity!.describe ?? '',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(40)),
                              ),
                            )),
                            Expanded(
                              flex: 1,
                              child: SizedBox(),
                            ),
                            Icon(
                              Icons.access_time,
                              color: Colors.white,
                            ),
                            Text(detailEntity!.stateName ?? '',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(40))),
                            SizedBox(
                              width: ScreenUtil().setWidth(30),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.person,
                              color: Colors.blue,
                            ),
                            Text(
                              '用户信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                            Expanded(
                              child: Container(),
                            ),
                            Offstage(
                              offstage: widget.view == "GetMySelfWaitDoWork"
                                  ? false
                                  : true,
                              child: Padding(
                                padding: EdgeInsets.all(5),
                                child: Text(
                                  detailEntity!.isRead == 1 ? "[已读]" : "[未读]",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(32),
                                      color: detailEntity!.isRead == 1
                                          ? Colors.green
                                          : Colors.red),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      getRow("联系人", detailEntity!.linkMan),
                      getPhoneRow("联系电话", detailEntity!.comePhone),
                      getRow("住户地址", detailEntity!.allName),
                      getRow("住户备注", detailEntity!.zHRemarks),
                      getRow("住户编码", detailEntity!.sfbm),
                      getRow("交费状态", ss),
                      getRow("是否VIP", getGNstate()),
                      getRow("天气状况", detailEntity!.weather),
                      getRow("控制信息", detailEntity!.azfsName),
                      Container(
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        color: Colors.grey,
                        height: ScreenUtil().setHeight(2),
                        width: ScreenUtil().screenWidth,
                      ),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.filter,
                              color: Colors.blue,
                            ),
                            Text(
                              '工单信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow("工单描述", detailEntity!.describe),
                      getRow("工单来源", detailEntity!.fromTypeName),
                      getPhoneRow("来电号码", detailEntity!.comePhone),
                      getRow("工单区域", detailEntity!.regionName),
                      getRow("工单类型", detailEntity!.typeName),
                      getRow("工单状态", detailEntity!.stateName),

                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.add_to_photos,
                              color: Colors.blue,
                            ),
                            Text(
                              '下单信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow("下单时间", detailEntity!.createDate),
                      // getRow("下单人员", detailEntity.createUserName),
                      getRow("修改时间",detailEntity!.updateDate??''),
                      getRow("处理时限", detailEntity!.limitTime.toString() + "小时"),
                      getRow("是否退回", detailEntity!.hBName),
                      getRow("是否超时", detailEntity!.ifyq),
                      getRow("紧急程度", detailEntity!.importName),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.assistant_photo,
                              color: Colors.blue,
                            ),
                            Text(
                              '接单信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow("接单时限", widget.jdsxTime == null ? "" : widget.jdsxTime!+ "小时"),
                      getRow("接单时间", detailEntity!.confirmTime),
                      getRow("是否超时", widget.isjdyq),
                      //附件展示
                      Offstage(
                        offstage: fileJdList.length>0?false:true,
                        child: GridView.builder(
                          padding: EdgeInsets.all(5),
                          physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3,
                            //纵轴间距
                            mainAxisSpacing: 10.0,
                            //横轴间距
                            crossAxisSpacing: 10.0,
                            childAspectRatio: 1,
                          ),
                          itemBuilder: (BuildContext context, int index) {
                            //Widget Function(BuildContext context, int index)
                            return getFileItem(fileJdList[index], index,showPhotoJdList);
                          },
                          itemCount: fileJdList.length,
                        ),
                      ),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.assistant_photo,
                              color: Colors.blue,
                            ),
                            Text(
                              '处理信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow("处理人员", detailEntity!.cLUserName),
                      getRow("处理部门", detailEntity!.departmentName),
                      getRow("处理结果", detailEntity!.resultName),
                      getRow("处理时间", detailEntity!.cLTime),
                      getRow("处理内容", detailEntity!.cLRemarks),
                      //附件展示
                      GridView.builder(
                        padding: EdgeInsets.all(5),
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          //纵轴间距
                          mainAxisSpacing: 10.0,
                          //横轴间距
                          crossAxisSpacing: 10.0,
                          childAspectRatio: 1,
                        ),
                        itemBuilder: (BuildContext context, int index) {
                          //Widget Function(BuildContext context, int index)
                          return getFileItem(fileList[index], index,showPhotoList);
                        },
                        itemCount: fileList.length,
                      ),
                      Offstage(
                        offstage: detailEntity!.ifhf == 1 ? false : true,
                        child: Column(
                          children: <Widget>[
                            Container(
                              height: ScreenUtil().setHeight(70),
                              padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Icon(
                                    Icons.star_border,
                                    color: Colors.blue,
                                  ),
                                  Text(
                                    '回访信息',
                                    style: TextStyle(
                                        color: Colors.blue,
                                        fontSize: ScreenUtil().setSp(40)),
                                  ),
                                ],
                              ),
                            ),
                            getRow("回访人员", detailEntity!.hFUser),
                            getRow("回访时间", detailEntity!.hFtime),
                            getRow("满意度：", detailEntity!.manYiDuName),
                            getRow("回访内容", detailEntity!.hFRemarks),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Offstage(
                  offstage: isloading,
                  child: SpinKitFadingCircle(
                    color: Colors.blue,
                    size: 50.0,
                  ),
                )
              ],
            ),
          ),
          widget.isDeliver!?
              //工单转交
          GestureDetector(
            onTap: () {
              getPersonData().then((value){
                showMyDialog();
              });
            },
            child: Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white),
                  color: Colors.blue),
              height: ScreenUtil().setHeight(100),
              width: ScreenUtil().screenWidth,
              child: Center(
                child: Text(
                  '转交工单',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ):
          Offstage(
              offstage: _isShow!,
              child: Container(
                height: ScreenUtil().setHeight(100),
                width: ScreenUtil().screenWidth,
                child: Row(
                  //offstage: isDelay,只要是我的工单都可以退回
                  children: <Widget>[
                    Offstage(
                      offstage:widget.view=='GetMySelfWaitDoWorkConfirm'?false:true,
                      child: Container(
                        width: MediaQuery.of(context).size.width / 2,
                        child: GestureDetector(
                          onTap: () {
                            //2022-02-14
                            //工单退回并同意之后，在工单调度中，重新指派给维修员并确认处理后，如果此处判断就无法退回
                            // if (detailEntity.ifhb == 1) {
                            //   Fluttertoast.showToast(msg: "该工单已退回");
                            //   return;
                            // }
                            if (detailEntity!.ifhb == 3) {
                              Fluttertoast.showToast(msg: "该工单已申请退回");
                              return;
                            }
                            if(isloading) {
                              showAlert();
                            }
                          },
                          child: Container(
                            decoration: BoxDecoration(
                                border: Border.all(color: Colors.blue),
                                color: Colors.white),
                            child: Center(
                              child: Text(
                                '申请退回',
                                style: TextStyle(
                                    color: Colors.blue,
                                    fontSize: ScreenUtil().setSp(30)),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                        onTap: () {
                          if(isloading) {
                            _goToDealPage();
                          }
                        },
                        child: Container(
                          color: Colors.blue,
                          child: Center(
                            child: Text(
                              '立即处理',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil().setSp(30)),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )),
        ],
      ),
    );
  }

  void showAlertReset() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("退回原因"),
            content: Container(
              width: ScreenUtil().setWidth(500),
              height: ScreenUtil().setHeight(200),
              color: Color(0xfff2f5f9),
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(width: 1.0, color: Colors.black12),
                  borderRadius: BorderRadius.circular(2.5),
//                                               color: Colors.white,
                ),
                child: TextField(
                  textAlign: TextAlign.start,
                  maxLines: null,
                  onSubmitted: (text) {
                    //内容提交(按回车)的回调

                    print('submit $text');
                  },
                  controller: _bzTextEditingController,
                  textInputAction: TextInputAction.done,
                  decoration: InputDecoration(
                    fillColor: Color(0xfff2f5f9),
                    contentPadding: EdgeInsets.all(10.0),
                    border: InputBorder.none,
                  ),
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  onPressed: () {

                    if(_bzTextEditingController.text==""){
                      Fluttertoast.showToast(msg: "请填写退回原因");
                      return;
                    }
                    Navigator.pop(context);
                    resetGongDan();
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  //退回工单
  Future resetGongDan() async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "ClientType": "phone",
      "ClientKey": aesData,
      "view": "GD_main",
      "cztype":"update",
      "fromdata":{
        "state":1,
        "tuihui_message":_bzTextEditingController.text
      },
      "ID": detailEntity!.iD,

    };
    print('退回工单data:$data');
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/formsavedata",
        data: data);
    if (mounted) {
      setState(() {
        isloading = true;
      });
    }
    print('response:${response.data}');
    if (response.data["Code"] == "200") {
      Fluttertoast.showToast(msg: "退回成功");
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
    }
  }

  void showAlert() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("退回原因"),
            content: Container(
              height: ScreenUtil().setHeight(120),
              child: TextField(
                controller: ideaController,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  //字母间距
                  letterSpacing: 0.5,
                  color: const Color(0xFF4A4A4A),
                ),
                decoration: InputDecoration(
                  hintStyle: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenUtil().setSp(28.0)),
                  hintText: "请输入退回原因",
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  onPressed: () {
                    if(ideaController.text.toString().length>0) {
                      Navigator.pop(context);
                      delay();
                    }else{
                      Fluttertoast.showToast(msg: '退回原因不能为空');
                    }

                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  Future delay() async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "Reason": ideaController.text.toString(),
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl  + "Work/RequestHuanBan",
        data: data);
    if (mounted) {
      setState(() {
        isloading = true;
      });
    }
    if (response.data["Code"] == "200") {
      Fluttertoast.showToast(msg: "提交成功");
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
    }
  }

  void _goToDealPage() async {
    print("hhaha");
    var oldDealBean = await DatabaseHelper().getVideo(widget.LSH);
    bool ifDraft = false;
    if (widget.view == "GetMySelfWaitDoWorkConfirm" && oldDealBean != null) {
      ifDraft = true;
    }
    Navigator.push(context, new MaterialPageRoute(builder: (context) {
      return DealDiaoDuPage(
        view: widget.view,
        detailStr: detailEntity,
        ifDraft: ifDraft,
        draftBean: oldDealBean,
      );
    })).then((data) {
      if (data) {

        getDetailData().then((onValue) {
          if (onValue != null) {
            getSFData();
            getFujianInfo();

            if (detailEntity!.resultName == '处理完成') {
              // 只有青铜峡项目有评价功能, 2021-10-06修改
              // showQr(context);
              if (mounted) {
                setState(() {
                  _isShow = true;
                });
              }
            }
          }
        });
      }
    });
  }

  Future showQr(BuildContext context) async {
    return showDialog<Null>(
        context: context, //BuildContext对象
        barrierDismissible: false,

        builder: (BuildContext context) {
          return new ShowQRCode( //调用对话框
            showData: WebConfig().evaluateurl+"?LSH="+widget.LSH!,
          );
        });
  }

  String? getGNstate() {
    String str = "";

    if (sfInfoEntity == null) {
      return str;
    } else {
      return sfInfoEntity!.isvip;
    }
  }

  Widget getRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectableText(
            str1 ?? '',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
            flex: 1,
            child: SelectableText(
              str2 ?? '',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
        ],
      ),
    );
  }

  Widget getPhoneRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.only(left: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectableText(
            str1 ?? '',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
              flex: 1,
              child: GestureDetector(
                child: Container(
//                color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: SelectableText(
                            str2 ?? '',
//                          maxLines: 2,
//                          overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: Colors.black87,
                                fontSize: ScreenUtil().setSp(35)),
                          ),
                        ),
                        Offstage(
                          offstage: str2 != "" ? false : true,
                          child: TextButton.icon(
                              onPressed: () {
                                _launchPhone(str2);
                              },
                              icon: Icon(
                                Icons.phone_in_talk,
                                size: ScreenUtil().setSp(38),
                              ),
                              label: Text(
                                "呼叫",
                                style:
                                    TextStyle(fontSize: ScreenUtil().setSp(28)),
                              )),
                        )
                      ],
                    )),
                onTap: () {
                  _launchPhone(str2);
                },
              )),
        ],
      ),
    );
  }

  _launchPhone(str) async {
    if (str != "" && str != null) {
      var url = 'tel:$str';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
        throw 'Could not launch $url';
      }
    } else {
      Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
    }
  }

  //获取详情
  Future getDetailData() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    int? delay = sharedPreferences.getInt("postid");
    if (delay == 4) {
      isDelay = false;
    }
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_GD_main",
      "wherestr": "LSH='" + widget.LSH! + "'",
      "sortName": "ID",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getrowdatanopage",
        data: data);
    print("获取详情：" + response.data.toString());
    isloading = true;
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          detailEntity =
              JsonConvert.fromJsonAsT(response.data["Data"]["data"][0]);
        }
      });
    }

    return response.data;
  }

  //获取住户收费信息
  Future getSFData() async {
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_Public_House",
      "wherestr": "House_id='" + detailEntity!.houseId.toString() + "'",
      "sortName": "Xq_name",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getrowdatanopage",
        data: data);
    print("收费"+response.data.toString());
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          if (response.data["Data"]["data"].length > 0) {
            sfInfoEntity = new ChargeDataDataData.fromJson(
                response.data["Data"]["data"][0]);
          }
        }
      });
    }
    return response.data;
  }

  // 返回每个隐藏的菜单项
  SelectView(String text, String id) {
    return PopupMenuItem<String>(
      value: id,
      child: Text(text),
    );
  }


  //获取接单确认附件
  Future getJieDanFujianInfo() async {
    fileJdList.clear();
    showPhotoJdList.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "ClientType": "phone",
      "ClientKey": aesData
    };

    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/GetSureWorkFuJian",
        data: data);

    print('接单确认附件===${response.data}');

    if (mounted) {
      setState(() {
        ShowFileListEntity showFileListEntity =
        ShowFileListEntity.fromJson(response.data);
        if (showFileListEntity.code == "200") {
          for (int i = 0; i < showFileListEntity.data!.length; i++) {
            fileJdList.add(showFileListEntity.data![i]);
          }
          for (int i = 0; i < fileJdList.length; i++) {
            var photoStr = {
              'image':
              WebConfig().webapiurl + "uploadfile/" + fileJdList[i].saveName!,
              'id': '$i'
            };

            showPhotoJdList.add(photoStr);
          }
          print("fileJdList'“" + showPhotoJdList.length.toString());
        }
      });
    }
  }

  //获取附件信息
  Future getFujianInfo() async {
    fileList.clear();
    showPhotoList.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print('===${WebConfig().baseUrl }');
    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/GetWorkFuJian",
        data: data);
    print('附件===${response.data}');
    if (mounted) {
      setState(() {
        ShowFileListEntity showFileListEntity =
            ShowFileListEntity.fromJson(response.data);
        if (showFileListEntity.code == "200") {
          for (int i = 0; i < showFileListEntity.data!.length; i++) {
            fileList.add(showFileListEntity.data![i]);
          }
          for (int i = 0; i < fileList.length; i++) {
            var photoStr = {
              'image':
                  WebConfig().webapiurl + "uploadfile/" + fileList[i].saveName!,
              'id': '$i'
            };

            showPhotoList.add(photoStr);
          }
          print("filelist'“" + showPhotoList.length.toString());
        }
      });
    }
  }

  Widget getFileItem(ShowFileListData fileList, int index,List photoList) {
    return GestureDetector(
      onTap: () {
        Navigator.push(context, new MaterialPageRoute(builder: (context) {
          return PhotoGalleryPage(
            index: index,
            photoList: photoList,
          );
        }));
      },
      child: Image.network(
        WebConfig().webapiurl + "uploadfile/" + fileList.saveName!,
        fit: BoxFit.fill,
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void showMyDialog() {
    //处理人员弹框
    showDialog(
        context: context,
        builder: (ctx) {
          return StatefulBuilder(
            builder: (context, state) {
              return SimpleDialog(
                title: Text("选择处理人员"),
                titlePadding: EdgeInsets.all(10),
                backgroundColor: Colors.white,
                elevation: 5,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(6))),
                children: <Widget>[
                  Container(
                    width: 200,
                    height: 300,
                    child: ListView.builder(
                      itemCount: personLists.length,
                      itemBuilder: (context, index) {
                        return Column(
                          children: <Widget>[
                            GestureDetector(
                              child: Container(
                                height: 50.0,
                                padding: EdgeInsets.only(left: 20.0),
                                width: 360.0,
                                child: Row(
                                  children: <Widget>[
                                    SizedBox(
                                      width: 10.0,
                                    ),
                                    Expanded(
                                        child: Text(
                                            "${personLists[index].realName}")),
                                  ],
                                ),
                              ),
                              onTap: () {
                                //取出点击的index
                                if(mounted){
                                  setState(() {
                                    isloading = false;
                                  });
                                }

                                  getPersonTongYiBuMen(personLists[index].iD)
                                      .then((data) {
                                        if(mounted){
                                          setState(() {
                                            isloading = true;
                                          });
                                        }

                                    print(
                                        "data===$data=${personLists[index].iD}");
                                    if (data) {
                                      showDeliverConfirmDialog(personLists[index].realName,personLists[index].iD);
                                    }

                                    state(() {});
                                  });


                                state(() {});
                              },
                            ),
                            Divider(),
                          ],
                        );
                      },
                    ),
                  )
                ],
              );
            },
          );
        });
  }

  //获取处理人员单选
  Future getPersonData() async {
    if(mounted){
      setState(() {
        isloading = false;
      });
    }
    personLists.clear();
    String aesData = await (AesUtil.encodeBase64());
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    var data = {
      "key": key,
      "Department_id": detailEntity!.departmentId,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/GetXiaFaRenYuan",
        data: data);
    personEntity = XiafaPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (personEntity.code == "200") {
      if (mounted) {
        setState(() {
          personEntity = XiafaPersonEntity.fromJson(response.data);
          personLists.addAll(personEntity.data!);
        });
      }
    }
    if(mounted){
      setState(() {
        isloading = true;
      });
    }

    return response.data;
  }

  //判断选中处理人员是否属于同一部门
  Future getPersonTongYiBuMen(personID) async {

    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "sdg": personID,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print("data===$data");
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/YanZhengBuMen",
        data: data);
    print(response.data.toString());
    if (response.data["Code"] == "200") {
      if (response.data["Data"] > 1) {
        Fluttertoast.showToast(msg: "请选择同一部门下的维修人员！");
        return false;
      } else {
        return true;
      }
    }
  }

  void showDeliverConfirmDialog(String? name,id){
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("将工单转交给"+name!),
            content: Container(
              height: ScreenUtil().setHeight(120),
              child: TextField(
                controller: deliverController,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  //字母间距
                  letterSpacing: 0.5,
                  color: const Color(0xFF4A4A4A),
                ),
                decoration: InputDecoration(
                  hintStyle: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenUtil().setSp(28.0)),
                  hintText: "请输入转交原因",
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                    goDeliver(id);
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
          ;
        });
  }

  //工单转交
  Future goDeliver(ids) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": detailEntity!.lSH,
      "ClientType": "phone",
      "ClientKey": aesData,
      'ZF_User_id':ids,
      'Remark':deliverController.text.toString()
    };
    print(data.toString());

    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/NiBuShiZhenZhengDeGaoXing",
        data: data);
    print(response.data.toString());

    if (response.data["Code"] == "200") {
      sendMessageGmAsync();
      Fluttertoast.showToast(msg: "操作成功");
      Navigator.pop(context);
      Navigator.pop(context);
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
    }
  }

  //转交成功后发送短信
  Future sendMessageGmAsync() async {

    print(WebConfig().sendMessageUrl+
    'Models/Handler2.ashx?method=SendMessageGmAsync&LSH='+detailEntity!.lSH!);

    Response response = await Dio().get(WebConfig().sendMessageUrl+
        'Models/Handler2.ashx?method=SendMessageGmAsync&LSH='+detailEntity!.lSH!,
        );
    print("发送短信: "+response.data.toString());


    return response.data;
  }

  //获取交费状态
  Future getFeeState() async {
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_Public_House",
      "wherestr": "House_id='" + detailEntity!.houseId.toString() + "'",
      "sortName": "Xq_name",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData,
      "sfbm":detailEntity!.sfbm
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getFeeYearPayInfo",
        data: data);
    print("收费数据"+response.data.toString());
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          if (response.data["Data"]["data"].length > 0) {
            ss='已缴费';
          }else{
            ss='未缴费';
          }
        }
      });
    }
    return response.data;
  }
}
